import mongodbHandle from '../handle/mongodbHandle'
import sessionHandle from '../handle/sessionHandle'
import rankHandle from '../handle/rankHandle'
import routes from './route'
var ObjectId = require('mongodb').ObjectId;
var utility = require("utility");
import app from '../app'
import * as moment from 'moment'
const jwt = require('jsonwebtoken');
import * as cluster from 'cluster'
import utils from '../serverCore/utils'
import redisHandle from '../handle/redisHandle';
import route from 'src/core/route/route';
import gameHandle from 'src/handle/gameHandle';
var fs = require('fs');

routes.setUserNotLogin('setVersion', [
    ['version', 'string'],
    ['data', 'array'],
    ['modify', 'number', false],
], async (msg) => {
    let {
        version,
        data,
        modify
    } = msg
    await mongodbHandle.gameDao.updateOne({ index: 1 }, {
        $set: {
            version: version,
        }
    })
    console.log("setVersion", version)
    app.version = version
    redisHandle.set(app.config.gameName + 'version' + app.env, version)
    let versions = version.split('.')
    let maxMax = Number(versions[0])
    let maxMin = Number(versions[1])
    await mongodbHandle.versionDao.updateOne({
        maxVersion: maxMax,
        minVersion: maxMin
    }, {
        $set: {
            maxVersion: maxMax,
            minVersion: maxMin,
            data: data,
            time: new Date().getTime(),
            modify: modify || 0
        }
    }, {
        upsert: true
    })
    if (cluster.isMaster) {
        for (const id in cluster.workers) {
            let worker = cluster.workers[id]
            if (worker) {
                worker.send({ "message": 'setVersion', version: version })
            }
        }
        app.arenaFork && app.arenaFork.send({ "message": "version", "version": app.version });
        // app.csFork.send({ "message": "version", "version": app.version });
    }
    return { err: 0 }

})



routes.setUserNotLogin('handle', [
    ['handle', 'number'],
], async (msg) => {
    console.log("handle", msg.handle)
    if (msg.handle == 1) {
        if (cluster.isMaster) {
            for (const id in cluster.workers) {
                let worker = cluster.workers[id]
                if (worker) {
                    worker.send({ "message": 'updatePlayer' })
                }
            }
            // app.csFork.send({ "message": "version", "version": app.version });
        }
    } else if (msg.handle == 2) {
        if (cluster.isMaster) {
            rankHandle.resetRank()
        }
    }
    return { err: 0 }

})

routes.setUserNotLogin('setServerState', [
    ['serverState', 'number'],
    ['stateText', 'string']
], async (msg, cb) => {
    app.serverState = msg.serverState
    app.stateText = msg.stateText || "服务器在维护中"
    if (cluster.isMaster) {
        for (const id in cluster.workers) {
            let worker = cluster.workers[id]
            worker.send({ "message": 'setServerState', serverState: app.serverState, stateText: app.stateText })
        }
    }
    return { err: 0 }
})

routes.setUserNotLogin('getVersionData', [
    ['max', 'number'],
    ['min', 'number'],
], async (msg, cb) => {
    let {
        max,
        min,
    } = msg
    let doc = await mongodbHandle.versionDao.findOne({
        maxVersion: max,
        minVersion: min
    })
    let data = []
    if (doc && doc.data) {
        data = doc.data
    }
    return { err: 0, data: data }
})

routes.setUserNotLogin('setCheat', [
    ['pID', 'string'],
    ['cheat', 'boolean'],
], async (msg, cb) => {
    let {
        pID,
        cheat
    } = msg
    let myData = await mongodbHandle.playerDao.findOne({ _id: ObjectId(pID) })
    if (myData) {
        await mongodbHandle.playerDao.updateOne({
            _id: ObjectId(pID)
        }, {
            $set: {
                cheat: cheat
            }
        })
    }
    return { err: 0 }
})

routes.setUserNotLogin('getVersionDatas', [], async (msg, cb) => {
    let docs = await mongodbHandle.versionDao.findByPageAndSort({
        modify: {
            $gte: 1
        }
    }, {
        maxVersion: -1,
        minVersion: -1
    }, 0, 25)
    return { err: 0, data: docs }
})

routes.setLogin('getGiftList', [], async (msg, session, cb) => {
    let data = { list: app.config.chargeTypes, vipTime: 0, buyGifts: {}, reserveNum: 0, yearVip: false }
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID)
    })

    if (doc) {
        let reserveNum = gameHandle.getReserveData()
        data.vipTime = doc.vipTime || 0
        data.buyGifts = doc.buyGifts || {}
        data.yearVip = doc.vip2 || false
        data.reserveNum = reserveNum
    }
    return { err: 0, data }
})


routes.setLogin('createOrder', [
    ['index', 'number'],
    ['type', 'number']
], async (msg, session, cb) => {
    let {
        index,
        type
    } = msg
    let chargetTypes = app.config.chargeTypes
    let chargetType = chargetTypes[index]
    if (!chargetType) {
        return { err: 0, code: 1 }
    }
    let doc = await mongodbHandle.playerDao.findOne({
        _id: ObjectId(session.pID),
    })
    if (!doc) {
        return { err: 0, code: 2 }
    }
    let buyGifts = doc.buyGifts || {}
    if (chargetType.buyType == 'unique' || chargetType.buyType == 'adventure') {

        if (buyGifts[doc.productID] != null) {
            // console.log('已经购买过了', session.pID, doc.productID)
            return { err: 0, code: 3 }
        }
    } else if (chargetType.buyType == 'day' || chargetType.buyType == 'week') {
        if (chargetType.buyType == 'day' && moment(buyGifts[doc.productID] || 0).isSame(moment(), 'day')) {
            // console.log('已经购买过每日礼包了', session.pID, doc.productID)
            return { err: 0, code: 4 }
        } else if (chargetType.buyType == 'week' && moment(buyGifts[doc.productID] || 0).isSame(moment(), 'week')) {
            // console.log('已经购买过每周礼包了', session.pID, doc.productID)
            return { err: 0, code: 5 }
        }
    }
    let orderID = utils.randomString(17)
    let money = chargetType.money
    await mongodbHandle.chargeDao.newAndSave(orderID, session.pID, money, index)
    return {
        err: 0,
        code: 0,
        data: {
            orderID: orderID,
            money: chargetType.money1 || money,
            name: chargetType.name,
        }
    }
})

//充值
routes.setUserNotLogin('leNotifycharge', [
    ['order_id', 'string'],
    ['pay_money', 'string', false],
    ['pay_time', 'string', false],
    ['exinfo', 'string', false],
    ['sign', 'string', false],
    ['role_id', 'string', false],
], async (msg, session) => {
    let {
        order_id, pay_money, pay_time, exinfo, payKey
    } = msg
    // console.log("leNotifycharge", msg)
    if (!exinfo) {
        return {
            err: 0, data: {
                "errno": 2,
                "msg": "exinfo不正确"
            }
        }
    }
    let doc = await mongodbHandle.chargeDao.findOne({ orderID: exinfo })
    if (!doc) {
        return {
            err: 0, data: {
                "errno": 3,
                "msg": "订单不存在"
            }
        }
    }
    if (doc.isPay) {
        return {
            err: 0, data: {
                "errno": 1,
                "msg": "订单已经发货"
            }
        }
    }


    //********** */
    if (doc.productID) {
        let player = await mongodbHandle.playerDao.findOne({ _id: ObjectId(doc.pID) })
        let buyGifts = player.buyGifts || {}
        let amount = 0
        let chargetTypes = app.config.chargeTypes
        let chargeType = chargetTypes[doc.productID]
        if (Number(msg.pay_money) < chargeType.money * 99) {
            return {
                err: 0, data: {
                    "errno": 4,
                    "msg": "订单金额",
                }
            }
        }
        await mongodbHandle.chargeDao.updateOne({ orderID: exinfo }, {
            $set: {
                isPay: true,
                payMoney: Number(msg.pay_money),
            }
        })

        let oChargeMoney = player.chargeMoney || 0
        // console.log('支付成功', order_id)
        if (chargeType) {
            // console.log('发送礼包', chargeType.items)
            if (chargeType.buyType == 'monthVip') {
                let vipTime = (player.vipTime || new Date().getTime())
                if (vipTime < moment().valueOf()) {
                    vipTime = moment().valueOf()
                }
                await mongodbHandle.playerDao.updateOne({
                    _id: ObjectId(doc.pID)
                }, {
                    $set: {
                        chargeMoney: oChargeMoney + (chargeType.money || 0),
                        vipTime: vipTime + 30 * 24 * 60 * 60 * 1000
                    }
                })
            } else  if (chargeType && chargeType.items) {
                if (chargeType.buyType == 'unique' || chargeType.buyType == 'adventure') {
                    if (buyGifts[doc.productID] == null || chargeType.type == 0) {
                        let items = []
                        for (let i = 0; i < chargeType.items.length; i++) {
                            items.push(chargeType.items[i]);
                        }
                        if (chargeType.attach && chargeType.attach.addPer) {
                            let addDiamond = 0
                            for (let index = 0; index < items.length; index++) {
                                const item = items[index];
                                if (item[0] == 'diamond') {
                                    addDiamond += item[1]
                                }
                            }
                            addDiamond = Math.floor(addDiamond * chargeType.attach.addPer / 100)
                            addDiamond > 0 && items.push(['diamond', addDiamond])
                        }
                        await mongodbHandle.mailDao.newAndSave(doc.pID, chargeType.name, items, [])
                    } else {
                        // console.log('已经购买过了', order_id, doc.productID)
                    }
                    if(chargeType.yearVip){
                        await mongodbHandle.playerDao.updateOne({
                            _id: ObjectId(doc.pID)
                        }, {
                            $set: {
                                vip2: true
                            }
                        })

                        if (cluster.isMaster) {
                            for (const id in cluster.workers) {
                                let worker = cluster.workers[id]
                                if (worker) {
                                    worker.send({ "message": 'updatePlayerYearVip', 'pID': doc.pID})
                                }
                            }
                        }
                    }
                } else if (chargeType.buyType == 'diamond') {
                    let items = []
                    for (let i = 0; i < chargeType.items.length; i++) {
                        items.push(chargeType.items[i]);
                    }
                    if ((buyGifts[doc.productID] == null || chargeType.type == 0) && chargeType.attach && chargeType.attach.addPer) {
                        let addDiamond = 0
                        for (let index = 0; index < items.length; index++) {
                            const item = items[index];
                            if (item[0] == 'diamond') {
                                addDiamond += item[1]
                            }
                        }
                        addDiamond = Math.floor(addDiamond * chargeType.attach.addPer / 100)
                        addDiamond > 0 && items.push(['diamond', addDiamond])
                    }
                    await mongodbHandle.mailDao.newAndSave(doc.pID, chargeType.name, items, [])
                } else {
                    let items = chargeType.items
                    await mongodbHandle.mailDao.newAndSave(doc.pID, chargeType.name, items, [])
                }
                // 更新购买时间
                buyGifts[doc.productID] = moment().valueOf()
                await mongodbHandle.playerDao.updateOne({
                    _id: ObjectId(doc.pID)
                }, {
                    $set: {
                        chargeMoney: oChargeMoney + (chargeType.money || 0),
                        buyGifts: buyGifts
                    }
                })
            }
        }

        gameHandle.sendCumulativeRecharge(doc.pID, oChargeMoney + (chargeType.money || 0))
    }
    return {
        err: 0, data: {
            "errno": 1,
            "msg": "成功"
        }
    }
})

//充值
routes.setUserNotLogin('charge', [
    ['productID', 'any'],
    ['pID', 'any'],
    ['amount', 'any'],
    ['orderID', 'any'],
], async (msg, session, cb) => {
    let {
        productID, pID, amount, orderID
    } = msg

    let doc = await mongodbHandle.chargeDao.findOne({ orderID: orderID })
    if (!doc) {
        await mongodbHandle.chargeDao.newAndSave(orderID, pID, amount, productID)
    } else if (doc && doc.isPay) {
        return { err: 1 }
    }
    let flag = false
    if (productID) {
        let playerDoc = await mongodbHandle.playerDao.findOne({ id: pID })
        if (!playerDoc) {
            return { err: 2 }
        }
        if (productID === "virusmonth") {
            let vipTime = (playerDoc.vipTime || new Date().getTime())
            if (vipTime < moment().valueOf()) {
                vipTime = moment().valueOf()
            }
            vipTime += 30 * amount * 24 * 60 * 60 * 1000
            await mongodbHandle.playerDao.updateOne({
                id: pID
            }, {
                $set: {
                    vipTime: vipTime
                }
            })
            flag = true
        } else if (productID === "virusgift") {
            let gold = ['diamond', 2500 * amount]
            let items1 = [gold, ['vipExp', 30 * amount]]
            let items2 = []
            mongodbHandle.mailDao.newAndSave(playerDoc._id.toString(), '钻石礼包x' + amount, items1, items2)
            flag = true

            let doc = await mongodbHandle.playerDao.findOne({ _id: playerDoc._id })
            if (doc) {
                await mongodbHandle.playerDao.updateOne({
                    _id: playerDoc._id
                }, {
                    $set: {
                        chargeMoney: (doc.chargeMoney || 0) + 30 * amount
                    }
                })
            }
        }

    }
    if (flag) {
        await mongodbHandle.chargeDao.updateOne({ orderID: orderID }, {
            $set: {
                isPay: true,
            }
        })
    }
    return { err: 0 }
})



routes.setUserNotLogin('getInterface', null, async (data) => {
    return {
        err: 0, data: {
            login: Object.keys(routes.login),
            userNotLogin: Object.keys(routes.userNotLogin),
            notLogin: Object.keys(routes.notLogin),
            validationData: routes.validationData,
        }
    }
})

routes.setLogin('getT', [
    ["sa", 'number', false]
], async (msg, session) => {
    if (msg.sa && session.isClientLocal == false) {
        let doc = await mongodbHandle.playerDao.findOne({
            _id: ObjectId(session.pID),
        })
        let nowTime = new Date().getTime()
        if (msg.sa < doc.saveAmount) {
            let clientLocalTime = doc.clientLocalTime || nowTime
            if (clientLocalTime < nowTime) {
                clientLocalTime = nowTime
            }
            clientLocalTime = clientLocalTime + 10 * 60 * 1000
            await mongodbHandle.playerDao.updateOne({
                _id: ObjectId(session.pID),
            }, {
                $set: {
                    saveAmount: 0,
                    clientLocalTime: clientLocalTime
                }
            })
            return { err: 3 }
        }
    }
    return {
        err: 0, data: {
            version: app.version,
            minVersion: app.minVersion,
            time: new Date().getTime(),
            dtime: moment().startOf('day').valueOf()
        }
    }
})


routes.setUserNotLogin('writeGameConfigFile', [
    ['configByIDData', 'any'],
    ['gameConfigData', 'any'],
    ['rMapData', 'any', false],
    ['path', 'string'],
], async (msg, session) => {
    let { configByIDData, gameConfigData, path, rMapData } = msg


    let str1 = `export let configByIDCopy = '${configByIDData}';`
    fs.writeFile(path + "//copyConfig//configByIDData.ts", str1, function (error) { });
    // fs.writeFile(path + "//src//core//config//configByIDData.ts", str1, function (error) { });

    let data1 = fs.readFileSync(path + "//copyConfig//configByIDData.ts", 'utf8');
    if (data1 && data1 == str1) {
      
    } else {
     
        fs.writeFile(path + "//copyConfig//configByIDData.ts", str1, function (error) { });
        fs.writeFile(path + "//src//core//config//configByIDData.ts", str1, function (error) { });
    }

    let str2 = `export let gameConfigCopy = '${gameConfigData}';`
    let data2 = fs.readFileSync(path + "//copyConfig//gameConfigData.ts", 'utf8');
    if (data2 && data2 == str2) {
      
    } else {
       
        fs.writeFile(path + "//copyConfig//gameConfigData.ts", str2, function (error) { });
        fs.writeFile(path + "//src//core//config//gameConfigData.ts", str2, function (error) { });
    }
    if (rMapData) {
        let str3 = `export let rMapData = ${rMapData};`
        fs.writeFile(path + "//src//core//utils//rMapData.ts", str3, function (error) { });
    }
    return {
        err: 0
    }
})
